import sys
import hashlib
import sqlite3
import os
import qdarkstyle
import webbrowser
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QUrl, QDate
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QIcon, QFont
from PyQt5.QtWebEngineWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from MainWindow import Ui_Form
from subwindow import Ui_Form_2
from PyQt5.QtSql import *
import numpy as np
import pandas as pd
import json
from pyecharts.charts import Bar, Map
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from collections import Counter
from selenium import webdriver
from sqlalchemy import create_engine
from threading import Thread
from pandas.tseries.offsets import *
from datetime import datetime


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("数据库实验")
        self.setWindowIcon(QIcon("./images/python.png"))
        self.status = self.statusBar()
        self.status.showMessage("作者QQ41413233,wang安专业")
        self.resize(1000, 700)
        self.center()
        self.p = Thread(target=self.data_process)#开启多线程，要不然刷新数据时软件就只能刷新不动了，其他的什么用不了。
        self.link_database()  # 连接数据库
        self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        self.setWindowOpacity(0.9) # 设置窗口透明度
        self.init_top_leftButton()
        #self.setWindowFlag(Qt.FramelessWindowHint) # 隐藏边框，
        self.init_top_right_window()
        self.init_connect()

    def link_database(self):
        # 连接数据库
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("./爬虫数据和database/test.db")
        self.model = QSqlTableModel()
        self.db.open()
        if not self.db.open():
            QMessageBox.critical(
                self, "无法打开数据库", "Sqlite3不支持", QMessageBox.Cancel)
            return False

    def init_connect(self):
        self.vertify_button.clicked.connect(self.show_vertify_page)
        self.login_button.clicked.connect(self.show_login_page)
        self.info_manage.clicked.connect(self.show_manage_info)
        self.quit_button.clicked.connect(self.quit_operation)
        self.intro_button.clicked.connect(self.show_introduction)
        self.radio_btn_admin.toggled.connect(self.change_button_status1)
        self.radio_btn_user.toggled.connect(self.change_button_status2)
        self.ok_button.clicked.connect(self.confirm_passwd)  # 确认密码
        self.cancel_button.clicked.connect(self.line_clear)
        self.info_ok.clicked.connect(self.add_user)
        self.info_cancel.clicked.connect(self.line_clear2)
        self.register_confirm.clicked.connect(self.add_admin_user)
        self.register_delete.clicked.connect(self.delete_admin_user)
        self.register_list.itemClicked.connect(self.current_index_change)
        self.query_button.clicked.connect(self.query)
        self.insert_oneline_button.clicked.connect(self.insert_oneline)
        self.find_row_button.clicked.connect(self.find_row)
        self.del_oneline_button.clicked.connect(self.del_oneline)
        self.del_all_button.clicked.connect(self.del_all)
        self.random_button.clicked.connect(self.random_data)
        self.insert_button.clicked.connect(self.insert)
        self.delete_button.clicked.connect(self.delete)
        self.China_button.clicked.connect(self.show_China)
        self.World_button.clicked.connect(self.show_World)
        self.temperature_button.clicked.connect(self.show_temperature)
        #self.map_button.clicked.connect(self.show_map)
        self.refresh_button.clicked.connect(self.refresh_data)#刷新疫情数据

    def current_index_change(self, item):
        self.select_item = item.text()  # 保存所点击的admin

    def line_clear(self):
        self.user_line.clear()
        self.passwd_line.clear()

    def line_clear2(self):
        self.student_name.clear()
        self.student_id.clear()
        self.province.setCurrentIndex(0)

    def delete_admin_user(self):
        q = QSqlQuery()
        text, ok = QInputDialog.getText(self, "密码", '请输入最高管理员密码:')
        text_hash = hashlib.md5(text.encode('utf-8')).hexdigest()
        if ok and text_hash == self.admin_hash:
            q.exec_("delete from Admin where name ='%s'" % self.select_item)
            QMessageBox.information(
                None, "完成", "删除成功,下次登录刷新", QMessageBox.Cancel)
        elif not ok:
            pass
        else:
            QMessageBox.warning(self, '警告', '最高管理员密码输入错误',
                                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def add_user(self):
        q = QSqlQuery()
        q.exec_("insert into Student values(\"{}\", \"{}\", \"{}\")".format(self.student_name.text(), self.student_id.text(),
                                                                            self.province.currentText()))  # 注意还要转义
        QMessageBox.information(None, "完成", "添加成功", QMessageBox.Cancel)

    def add_admin_user(self):
        q = QSqlQuery()
        register_pd_hash = hashlib.md5(
            self.register_pd.text().encode('utf-8')).hexdigest()
        text, ok = QInputDialog.getText(self, "密码", '请输入最高管理员密码:')
        text_hash = hashlib.md5(text.encode('utf-8')).hexdigest()
        if ok and text_hash == self.admin_hash:
            q.exec_("insert into Admin values(\"{}\", \"{}\")".format(
                self.register_id.text(), register_pd_hash))  # 注意还要转义
            QMessageBox.information(None, "完成", "添加成功", QMessageBox.Cancel)
        elif not ok:
            pass
        else:
            QMessageBox.warning(self, '警告', '最高管理员密码输入错误',
                                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def confirm_passwd(self):

        user_id = self.user_line.text()
        user_pd = self.passwd_line.text()
        user_pd_hash = hashlib.md5(user_pd.encode('utf-8')).hexdigest()
        #查询数据库中管理人员信息
        q = QSqlQuery()      
        q.exec_('select * from Admin where name = "%s"' % user_id)
        #默认初始化为Null
        name = 0
        password = ''

        if q.next():
            name = q.value(0)
            password = q.value(1)
            #print(password)
        
        if name and password:#如果有数据，就是查询到了，会进行下面操作
            if password == user_pd_hash:
                self.info_manage.setEnabled(True)#解锁信息管理按钮，默认是不可以点击的
                QMessageBox.information(
                    None, ("友情提示"), ("登录成功"), QMessageBox.Cancel)
                self.login_button.setEnabled(False)
            else:
                QMessageBox.information(
                    None, ("友情提示"), ("密码输入错误"), QMessageBox.Cancel)

        else:
            QMessageBox.information(
                None, ("友情提示"), ("没有该用户"), QMessageBox.Cancel)

        q.exec_('select * from Admin where name = "hahaha" ')
        while q.next():
            self.admin_hash = q.value(1)
        #print(self.admin_hash)验证时留下的数据

    def change_button_status1(self):
        self.vertify_button.setEnabled(True)
        self.login_button.setEnabled(True)

    def change_button_status2(self):
        self.login_button.setEnabled(False)

    def init_top_leftButton(self):
        top_left_button = QFrame()
        top_left_button.setFrameShape(QFrame.StyledPanel)
        top_left_button_layout = QVBoxLayout(top_left_button)
        self.vertify_button = QPushButton("确认身份")
        self.vertify_button.setIcon(QIcon('./images/cartoon1.ico'))
        self.vertify_button.setFixedSize(100, 40)
        top_left_button_layout.addWidget(self.vertify_button)
        self.login_button = QPushButton("登录")
        self.login_button.setIcon(QIcon('./images/cartoon2.ico'))
        self.login_button.setFixedSize(100, 40)
        self.login_button.setEnabled(False)
        top_left_button_layout.addWidget(self.login_button)
        self.info_manage = QPushButton("信息管理")  # 管理员可以使用
        self.info_manage.setIcon(QIcon('./images/cartoon3.ico'))
        self.info_manage.setFixedSize(100, 40)
        self.info_manage.setEnabled(False)
        top_left_button_layout.addWidget(self.info_manage)
        self.quit_button = QPushButton("退出")
        self.quit_button.setIcon(QIcon('./images/cartoon4.ico'))
        self.quit_button.setFixedSize(100, 40)
        top_left_button_layout.addWidget(self.quit_button)
        self.China_button = QPushButton("国内数据")
        self.China_button.setIcon(QIcon('./images/cartoon5.ico'))
        self.China_button.setFixedSize(100, 40)
        top_left_button_layout.addWidget(self.China_button)
        self.World_button = QPushButton("全球数据")
        self.World_button.setIcon(QIcon('./images/cartoon6.ico'))
        self.World_button.setFixedSize(100, 40)
        top_left_button_layout.addWidget(self.World_button)
        self.refresh_button = QPushButton('点击刷新')
        self.refresh_button.setIcon(QIcon('./images/cartoon7.ico'))
        self.refresh_button.setFixedSize(100,40)
        top_left_button_layout.addWidget(self.refresh_button)
        self.map_button = QPushButton('疫情地图')
        self.map_button.setFixedSize(100,40)
        self.map_button.setIcon(QIcon('./images/cartoon8.ico'))
        top_left_button_layout.addWidget(self.map_button)
        self.temperature_button = QPushButton('个人体温表')
        self.temperature_button.setIcon(QIcon('./images/cartoon9.ico'))
        self.temperature_button.setFixedSize(100,40)
        top_left_button_layout.addWidget(self.temperature_button)
        self.intro_button = QPushButton("文档介绍")  # 使用介绍
        self.intro_button.setIcon(QIcon('./images/python.png'))
        self.intro_button.setFixedSize(100, 40)
        top_left_button_layout.addWidget(self.intro_button)
        top_left_button_layout.addStretch(1)
        self.splitter1 = QSplitter(Qt.Horizontal)
        self.splitter1.addWidget(top_left_button)

    def init_top_right_window(self):

        top_right_widget = QFrame()
        top_right_widget.setFrameShape(QFrame.StyledPanel)
        self.top_right_widget_layout = QStackedLayout(top_right_widget)
        # top_right_widget.resize(,600)
        self.splitter1.addWidget(top_right_widget)
        self.setCentralWidget(self.splitter1)

        # 1 确认身份 界面
        # 管理员身份
        self.radio_btn_admin = QRadioButton()
        self.radio_btn_admin.setText("我是管理员，来输入数据的")
        # 游客身份 二者只能选一个
        self.radio_btn_user = QRadioButton()
        self.radio_btn_user.setText("我是游客，就来看看")
        # 以垂直布局管理器管理 并设置为第一个界面
        radio_btn_layout = QVBoxLayout()
        radio_btn_widget = QWidget()
        radio_btn_layout.addWidget(self.radio_btn_admin)
        radio_btn_layout.addWidget(self.radio_btn_user)
        radio_btn_widget.setLayout(radio_btn_layout)
        self.top_right_widget_layout.addWidget(radio_btn_widget)

        # 2 登录界面
        # name passed layout
        self.user_line = QLineEdit()
        self.user_line.setPlaceholderText("请输入账号:")
        self.user_line.setFixedWidth(400)
        self.passwd_line = QLineEdit()
        self.passwd_line.setPlaceholderText("请输入密码:")
        self.passwd_line.setFixedWidth(400)
        self.passwd_line.setEchoMode(QLineEdit.Password)
        # login button layout
        login_button_layout = QHBoxLayout()
        self.ok_button = QPushButton("确定")
        self.cancel_button = QPushButton("清除")
        self.ok_button.setFixedWidth(100)
        self.cancel_button.setFixedWidth(100)
        login_button_layout.addWidget(self.ok_button)
        login_button_layout.addWidget(self.cancel_button)
        # layout
        login_widget = QWidget()
        login_layout = QVBoxLayout(login_widget)
        login_layout.addWidget(self.user_line)
        login_layout.addWidget(self.passwd_line)
        login_layout.addLayout(login_button_layout)
        self.top_right_widget_layout.addWidget(login_widget)

        # 3 用户管理界面
        info_manage_tab = QTabWidget()
        self.top_right_widget_layout.addWidget(info_manage_tab)
        admin_info = QWidget()
        people_manage = QWidget()
        people_info = QWidget()
        # temperature = QWidget()
        info_manage_tab.addTab(admin_info, "账户管理")
        info_manage_tab.addTab(people_manage, "添加人员")
        info_manage_tab.addTab(people_info, "人员信息")
        # info_manage_tab.addTab(temperature,'人员体温')

        # 3.1 账户管理界面
        self.register_id = QLineEdit()
        self.register_id.setPlaceholderText("请输入账户")
        self.register_id.setFixedWidth(300)
        self.register_pd = QLineEdit()
        self.register_pd.setPlaceholderText("请输入密码")
        self.register_pd.setEchoMode(QLineEdit.Password)
        self.register_pd_again = QLineEdit()
        self.register_pd.setFixedWidth(300)
        self.register_pd_again.setPlaceholderText("请确认密码")
        self.register_pd_again.setEchoMode(QLineEdit.Password)
        self.register_pd_again.setFixedWidth(300)
        register_layout = QVBoxLayout()
        register_layout.addWidget(self.register_id)
        register_layout.addWidget(self.register_pd)
        register_layout.addWidget(self.register_pd_again)
        self.register_confirm = QPushButton("确定提交")
        self.register_delete = QPushButton("确认删除")
        self.register_confirm.setFixedSize(100, 30)
        self.register_delete.setFixedSize(100, 30)
        self.register_list = QListWidget()  # 添加一个table用于显示用户信息
        register_button_layout = QHBoxLayout()
        register_button_layout.addWidget(self.register_confirm)
        register_button_layout.addWidget(self.register_delete)
        register_layout.addLayout(register_button_layout)
        admin_info_label = QLabel("以下是所有高级管理员")
        register_layout.addWidget(admin_info_label)
        self.register_list.setWindowTitle("所有管理员用户名称")
        admin_list = self.get_admin_name()
        self.register_list.addItems(admin_list)
        register_layout.addWidget(self.register_list)
        admin_info.setLayout(register_layout)

        # 3.2 人员信息界面，这一段基本没什么用，但是又懒得删除了，就保留在这儿，最初想法是做一个体温统计，给非管理员用户填个人信息的
        add_info_layout = QHBoxLayout()  # 增加学生信息布局
        self.student_name = QLineEdit()
        self.student_name.setPlaceholderText("请输入姓名")
        self.student_name.setFixedWidth(120)
        self.student_id = QLineEdit()
        self.student_id.setPlaceholderText("请输入学号")
        self.student_id.setFixedWidth(120)
        self.province = QComboBox()
        self.province.addItems(["北京(京)", "天津(津)", "上海(沪)", "重庆(渝)", "河北(冀)", "河南(豫)", "云南(云)", "辽宁(辽)", "黑龙江(黑)",
                                "湖南(湘)", "安徽(皖)", "山东(鲁)", "新疆(新)", "江苏(苏)", "浙江(浙)", '江西(赣)', '湖北(鄂)', '广西(桂)', '甘肃(甘)', '山西(晋)',
                                '内蒙古(蒙)', '陕西(陕版)', '吉林(吉)', '福建(闽)', '贵州(贵)', '广东(粤)', '青海(青)', '西藏(藏)', '四川(川)', '宁夏(宁)', '海南(琼)',
                                '台湾(台)', '香港(港)', '澳门(澳)'])
        self.province.setFixedWidth(120)
        add_info_layout.addWidget(self.student_name)
        add_info_layout.addWidget(self.student_id)
        add_info_layout.addWidget(self.province)
        self.info_ok = QPushButton("确定")
        self.info_cancel = QPushButton("取消")
        self.info_ok.setFixedWidth(150)
        self.info_cancel.setFixedWidth(150)
        info_button_layout = QHBoxLayout()
        info_button_layout.addWidget(self.info_ok)
        info_button_layout.addWidget(self.info_cancel)
        manage_info_layout = QVBoxLayout()
        manage_info_layout.addLayout(add_info_layout)
        manage_info_layout.addLayout(info_button_layout)
        people_manage.setLayout(manage_info_layout)

        # 3.3 人员管理界面
        people_info_layout = QHBoxLayout()
        people_left_layout = QVBoxLayout()
        self.insert_button = QPushButton("当前位置插入")
        self.insert_button.setFixedSize(80, 30)
        self.random_button = QPushButton("随机生成数据")
        self.random_button.setFixedSize(80, 30)
        self.delete_button = QPushButton("当前位置删除")
        self.delete_button.setFixedSize(80, 30)
        self.query_button = QPushButton("查看所有")
        self.query_button.setFixedSize(80, 30)
        self.insert_oneline_button = QPushButton("尾部插入")
        self.insert_oneline_button.setFixedSize(80, 30)
        self.find_row_button = QPushButton("当前位置")
        self.find_row_button.setFixedSize(80, 30)
        self.del_oneline_button = QPushButton('尾部删除')
        self.del_oneline_button.setFixedSize(80, 30)
        self.del_all_button = QPushButton('删除所有')
        self.del_all_button.setFixedSize(80, 30)
        people_left_layout.addWidget(self.query_button)
        people_left_layout.addWidget(self.random_button)
        people_left_layout.addWidget(self.insert_button)
        people_left_layout.addWidget(self.delete_button)
        people_left_layout.addWidget(self.insert_oneline_button)
        people_left_layout.addWidget(self.find_row_button)
        people_left_layout.addWidget(self.del_oneline_button)
        people_left_layout.addWidget(self.del_all_button)
        people_left_layout.addStretch(1)
        people_info_layout.addLayout(people_left_layout)
        self.view = QTableView()
        people_info_layout.addWidget(self.view)
        # self.table_view = QTableView()
        # people_info_layout.addWidget(self.table_view)
        people_info.setLayout(people_info_layout)
        # self.top_right_widget_layout.setCurrentIndex(2)
        # self.setCentralWidget(top_right_widget)


        # 4 国内疫情
        self.view_1 = QTableView()
        self.top_right_widget_layout.addWidget(self.view_1)

        # 5 全球疫情
        self.view_2 = QTableView()
        self.top_right_widget_layout.addWidget(self.view_2)

        #6 疫情地图
        self.map_info = QWebEngineView()
        url = (os.getcwd()+'/map.html')
        self.map_info.load(QUrl.fromLocalFile(url))
        self.top_right_widget_layout.addWidget(self.map_info)
        
        # 7 体温表
        self.temperature_info = QWebEngineView()
        # url = r'/home/ymy/Documents/pyqt5实战/数据库实验/temperature.html'
        url_1 = (os.getcwd()+'/temperature.html')#必须是绝对路径
        self.temperature_info.load(QUrl.fromLocalFile(url_1))
        # self.browser.page().runJavaScript(jscode)
        self.top_right_widget_layout.addWidget(self.temperature_info)

        # 7 文档介绍
        intro_text = QTextEdit()
        intro_text.setHtml(
            "<font color='red' size='6'><red>好像没啥可以说的\n写的不好，多多包含。</font>")
        self.top_right_widget_layout.addWidget(intro_text)

    def get_admin_name(self):
        # SELECT 列名 FROM 表名;
        q = QSqlQuery()
        command = "SELECT name FROM Admin"
        value_list = []
        if q.exec_(command):
            name_index = q.record().indexOf("name")  # 获取列索引值
            while q.next():
                value = q.value(name_index)
                value_list.append(str(value))
        return value_list

    def show_vertify_page(self):
        self.top_right_widget_layout.setCurrentIndex(0)

    def show_login_page(self):
        self.top_right_widget_layout.setCurrentIndex(1)

    def show_manage_info(self):
        self.top_right_widget_layout.setCurrentIndex(2)

    def show_China(self):
        self.top_right_widget_layout.setCurrentIndex(3)
        self.show_China_info()

    def show_World(self):
        self.top_right_widget_layout.setCurrentIndex(4)
        self.show_World_info()

    def show_temperature(self):
        self.top_right_widget_layout.setCurrentIndex(5)
    def show_map(self):
        self.top_right_widget_layout.setCurrentIndex(6)
    def show_introduction(self):
        self.top_right_widget_layout.setCurrentIndex(7)

    # 4 quit界面，其实也没啥可以加的,直接不加界面了，点击时弹出一个对话框

    def quit_operation(self):
        message = QMessageBox.question(
            self, ' ', '确认退出吗？', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if message == QMessageBox.Yes:
            try:
                self.p.join()#关闭子线程
            except:#防止没有开启多线程，即没有刷新数据，也是最后调试时发现的小错误，没有try程序退出也不会出错，终端会显示警告
                pass
            self.db.close()#关闭数据库
            qApp = QApplication.instance()
            qApp.quit()#退出软件

    def center(self):
        '''
        获取桌面长宽
        获取窗口长宽
        移动
        '''
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    # 查找当前所在行数
    def find_row(self):
        self.status.showMessage("所在行数为{}，列数为{}".format(
            self.view.currentIndex().row() + 1, self.view.currentIndex().column() + 1))

    # 删除尾部一行
    def del_oneline(self):
        self.model.removeRow(self.model.rowCount())
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.select()
        self.view.setModel(self.model)
        self.view.show()

    def delete(self):
        self.model.removeRow(self.view.currentIndex().row())
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.select()
        self.view.setModel(self.model)
        self.view.show()

    def del_all(self):
        q = QSqlQuery()
        text, ok = QInputDialog.getText(self, "密码", '请输入最高管理员密码:')
        text_hash = hashlib.md5(text.encode('utf-8')).hexdigest()
        if ok and text_hash == self.admin_hash:
            q.exec_("delete from Student;")
            QMessageBox.information(
                None, "完成", "删除成功,下次登录刷新", QMessageBox.Cancel)
        elif not ok:
            pass
        else:
            QMessageBox.warning(self, '警告', '最高管理员密码输入错误',
                                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def insert(self):
        self.model.insertRows(self.view.currentIndex().row(), 1)
    # 插入一行

    def insert_oneline(self):
        self.model.insertRows(self.model.rowCount(), 1)
        # print(str(ret))

    def query(self):
        self.model.setTable("temperature")
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        # self.model.setFilter("id > 1")
        self.model.select()
        self.view.setModel(self.model)
        self.view.show()

    def random_data(self):#随机生成数据，防止麻烦了，可以自行修改
        d = pd.to_datetime(datetime.now())#当前时间
        d1 = d - DateOffset(days=15)#当前时间往前推移15天
        dates = pd.date_range(d1 , d).date#生成时间序列
        np.set_printoptions(precision=2)#保留两位小数
        data=pd.DataFrame(np.around(np.random.normal(36.5,0.1,(16,4)),2),index=dates,columns=['张三','李四','王二麻子','大傻子'])
        #生成均值36.5，方差0.1的数据
        engine= create_engine('sqlite:///./爬虫数据和database/test.db')
        data.to_sql('temperature', engine,if_exists='replace')
        bar = Bar()#其实pyqt5展示html太慢了，此处等待一段时间，bar才会显示
        bar.add_xaxis(dates.tolist())
        bar.add_yaxis('张三',data['张三'].values.tolist())
        bar.add_yaxis('李四',data['李四'].values.tolist())
        bar.add_yaxis('王二麻子',data['王二麻子'].values.tolist())
        bar.add_yaxis('大傻子',data['大傻子'].values.tolist(),is_selected= False)
        #bar.reversal_axis()反转轴
        bar.set_global_opts(title_opts=opts.TitleOpts(title="个人体温信息"),yaxis_opts=opts.AxisOpts(min_='dataMin'))
        bar.render('temperature.html')

    def show_China_info(self):
        self.model.setTable("China")
        #self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.select()
        self.view_1.setModel(self.model)
        self.view_1.show()
    def show_World_info(self):
        self.model.setTable("Global")
        #self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.select()
        self.view_2.setModel(self.model)
        self.view_2.show()
    def refresh_data(self):
        self.p.start()

    def data_process(self):
        url = "http://zhongxinzhiyuan.cn/yiqing_real_time_map.html"
        # 使用谷歌浏览器应用程序chromedriver.exe打开网页，需要自己修改chromedriver.exe所在的路径
        driver = webdriver.Chrome("./爬虫数据和database/chromedriver")
        driver.get(url)
        def getdata_1(id):#如果子线程在此处意外退出，终端会显示一段信息，但是不影响主线程继续执行
            try:
                driver.find_element_by_id(id)
                #print(driver.find_element_by_id(id).text)
                text1 = driver.find_element_by_id(id).text
                #print(len(text1))
                #print(text1)
                return text1
            except:
                print('获取失败')
        
        dataid = ['table-provience']
        # 开始尝试爬取中国数据
        for num in range(len(dataid)):
            text_china = getdata_1(dataid[num])

        dataid = ['table-tr']
        # 开始尝试爬取全球数据
        for num in range(len(dataid)):
            text_global = getdata_1(dataid[num])
        if len(text_global):#为什么需要这个if 呢？ 
            #因为爬取过程耗时较长，若果关闭webdriver之前还没有成功获取数据，后面的数据解析肯定报错
            #先对数据进行简单的处理
            temp1 = text_china.split("\n")
            temp_China =[]
            for i in temp1:
                temp_China.append(i.split())
            a=pd.DataFrame(temp_China,columns = ["序号",'省份','现存确诊','累计确诊','治愈','死亡'] )
            China = a.iloc[:,1:]#删选后的中国疫情数据
            map_data = list(zip(a["省份"].tolist(),a['累计确诊'].tolist()))
            map = (
                Map(init_opts=opts.InitOpts(bg_color="#FFFAFA", theme=ThemeType.ESSOS, width=1000))
                .add("确诊人数", map_data)
                .set_global_opts(
                title_opts=opts.TitleOpts(title="fungis-基于James数据的疫情图"))
            )
            map.render('./map.html')
            temp1 = text_global.split("\n")
            temp_global =[]
            for i in temp1:
                temp_global.append(i.split())
            Global=pd.DataFrame(temp_global,columns = ["大陆",'国家','现存确诊','累计确诊','治愈','死亡'] )#筛选后的国际数据

            #存入数据库
            engine= create_engine('sqlite:///./爬虫数据和database/test.db')
            China.to_sql('China', engine,if_exists='replace',index = False)
            Global.to_sql('Global', engine,if_exists='replace',index = False)
            QMessageBox.information(None, ("友情提示"), ("刷新成功,务必关闭浏览器后再关闭此页面"), QMessageBox.Cancel)
        else:
            QMessageBox.information(None, ("友情提示"), ("刷新失败"), QMessageBox.Cancel)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    MainWindow = MainWindow()
    MainWindow.show()
    sys.exit(app.exec())
